import Vue from 'vue'
import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import router from '@/router'
import qs from 'qs'

axios.defaults.baseURL = ''

const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
})

//配置请求拦截
let LoadingStance = null
service.interceptors.request.use(
  (config) => {
    LoadingStance = Loading.service({ fullscreen: true })
    // if (localStorage.getItem('token')) {
    //   axios.defaults.headers.authorization = localStorage.getItem('token')
    // }
    //axios.defaults.headers.authorization =
    // window.sessionStorage.getItem('token')
    config.headers.authorization = window.sessionStorage.getItem('token')
    //console.log(config)
    return config
  },
  (error) => {
    //请求出错了(还没有发出去)
    return Promise.reject(error)
  }
)

//配置响应拦截
service.interceptors.response.use(
  (response) => {
    console.log('数据返回：',response)
    LoadingStance.close()
    const res = response.data
    if (Number(response.status) === 401) {
      // if (localStorage.getItem('token')) {
      router.push('/login')
      return
      // }
    }
    // if (parseInt(res.code) !== 200) {
    //   Message({
    //     message: res.msg || 'Error',
    //     type: 'error',
    //     duration: 3000,
    //   })
    // }
    return res
  },
  (error) => {
    // console.log('err' + error); // for debug
    Message({
      message: '请求失败请稍后重试！',
      type: 'error',
      duration: 3000,
    })
    LoadingStance.close()
    return Promise.reject(error)
    // const obj = {
    //   code: '9999',
    //   msg: '错误'
    // }
    // return obj
  }
)

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params: params,
      })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, qs.stringify(params))
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}

Vue.prototype.$http = service
